package com.hundsun.yr.universal.p2p.datahandler;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.base.BaseAppManager;
import com.hundsun.yr.universal.library.common.MD5Utils;
import com.hundsun.yr.universal.library.data.HSSharedPreferences;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.utils.MathUtils;
import com.hundsun.yr.universal.library.widget.HSToast;
import com.hundsun.yr.universal.p2p.bean.AdSlideBeen;
import com.hundsun.yr.universal.p2p.bean.LoginBeen;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Config;
import com.hundsun.yr.universal.p2p.config.Config.SPPath;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.Extras;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.interactor.impl.StringRequestInteractorImpl;
import com.hundsun.yr.universal.p2p.listener.BaseMultiLoadedListener;
import com.hundsun.yr.universal.p2p.ui.activity.LoginActivity;
import com.hundsun.yr.universal.p2p.ui.activity.OpenAccountBankActivity;
import com.hundsun.yr.universal.p2p.ui.activity.RegisterInputPhoneActivity;
import com.hundsun.yr.universal.p2p.ui.activity.RegisterValidateActivity;
import com.hundsun.yr.universal.p2p.utils.AndroidDes3Util;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.utils.GsonTool;
import com.hundsun.yr.universal.p2p.utils.Logs;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import de.greenrobot.event.EventBus;

/**
 * 注册数据处理基类
 *
 * @author tonglj
 */
public class RegisterValidateHandler extends BaseDataHandler {
    /**
     * 用于保存用户信息
     */
    private HSSharedPreferences sharedPreferences;
    private HSSharedPreferences mConfigSP;

    public RegisterValidateHandler(Context mContext) {
        super(mContext);
        sharedPreferences = new HSSharedPreferences(mContext, SPPath.file_userLoginedInfo);
        mConfigSP = new HSSharedPreferences(mContext, Config.SPPath.file_configInfo);
    }

    /**
     * 调用注册接口--通过反射的方式
     */
    protected void doRegister(Object... obj) {
        //网络注册
        String zwgt_data = BaseRequestTool2.getFormatedDateString();
        JSONObject map = new JSONObject();
        try {
            map.put("phone", obj[0].toString());
            map.put("passwd",MD5Utils.getMD5String(obj[1].toString()));
            map.put("code", obj[2].toString());
            map.put("inviter", obj[3].toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        JSONObject jsonParams = CommTool.getJSONParams(map, mConfigSP.getShareProf(TaskConstants.TASK_CONFIG), zwgt_data);

        StringRequestInteractorImpl requestinteractor = new StringRequestInteractorImpl(new BaseMultiLoadedListener<String>() {
            @Override
            public void onSuccess(String task_name, int event_tag, String data) {
                //注册成功
                Logs.d("反射注册成功RegisterValidateHandler", "注册data:" + data);
                try {
                    AdSlideBeen adSlideBeen = (AdSlideBeen) GsonTool.getInstanceByJson(AdSlideBeen.class, data);
                    switch (adSlideBeen.code) {
                        case Constants.REQUESTCODE_000000:
                            //网络请求成功,进行解密，存储相关数据
                            try {
                                // TODO: 2017/5/16 注册接口解析失败
                                new HSToast(mContext).getSingleLongToast(adSlideBeen.msg).show();
                                String decode = AndroidDes3Util.decode(adSlideBeen.data, mConfigSP.getShareProf(TaskConstants.TASK_CONFIG),
                                        (Date.parse(adSlideBeen.timestamp) + "").substring((Date.parse(adSlideBeen.timestamp) + "").length() - 8, (Date.parse(adSlideBeen.timestamp) + "").length()));
                                String[] split = decode.split("\\n");

                                LoginBeen loginBeen = (LoginBeen) GsonTool.getInstanceByJson(LoginBeen.class, split[1]);
                                //将获得的数据存起来
                                //存放token
                                sharedPreferences.putShareProf(UserInfo.TOKENID, loginBeen.token);
                                sharedPreferences.putBoolean(UserInfo.ISLOGIN, true);
                                //存放用户id
                                sharedPreferences.putShareProf(UserInfo.USER_NO, loginBeen.user_no);
                                //存放用户手机号
                                sharedPreferences.putShareProf(UserInfo.MOBILE, loginBeen.phone);
                                //存放账号，应该就是手机号
                                sharedPreferences.putShareProf(UserInfo.ACCOUNT, loginBeen.phone);
                                //身份证
                                sharedPreferences.putShareProf(UserInfo.CERT_NO, loginBeen.cert_no);
                                sharedPreferences.putShareProf(UserInfo.LENDER, loginBeen.is_lender);
                                if (loginBeen.depository_bank_no != null && !loginBeen.depository_bank_no.isEmpty()) {
                                    //已开户
                                    sharedPreferences.putShareProf(UserInfo.IF_ACCOUNT, "YES");
                                } else {
                                    //已开户
                                    sharedPreferences.putShareProf(UserInfo.IF_ACCOUNT, "NO");
                                }

                                /**
                                 * 用户是否设置了交易密码
                                 */
                                if (loginBeen.set_paypwd_flag != null && !loginBeen.set_paypwd_flag.isEmpty()) {
                                    if (TextUtils.equals(loginBeen.set_paypwd_flag, "1")) {
                                        //已经设置交易密码
                                        sharedPreferences.putShareProf(UserInfo.IF_PAYPWD, "YES");
                                    } else {
                                        sharedPreferences.putShareProf(UserInfo.IF_PAYPWD, "NO");
                                    }
                                } else {
                                    sharedPreferences.putShareProf(UserInfo.IF_PAYPWD, "NO");
                                }

                                /**
                                 * 保存用户等级
                                 */
                                Logs.e("用户风险等级： " + loginBeen.level);
                                if (loginBeen.level != null && !loginBeen.level.isEmpty()){
                                    sharedPreferences.putShareProf(UserInfo.USERLEVEL,loginBeen.level);
                                } else {
                                    sharedPreferences.putShareProf(UserInfo.USERLEVEL,"0");
                                }

                                /**
                                 * 保存用户银行卡手机号
                                 */
                                if (loginBeen.depository_bank_mobile != null && !loginBeen.depository_bank_mobile.isEmpty()){
                                    sharedPreferences.putShareProf(UserInfo.BANKMOBILE,loginBeen.depository_bank_mobile);
                                } else {
                                    sharedPreferences.putShareProf(UserInfo.BANKMOBILE,"");
                                }

                                if (loginBeen.ctime != null && !loginBeen.ctime.isEmpty()){
                                    //将时间转换成时间戳
                                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//24小时制
                                    //      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");//12小时制
                                    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
                                    long time = simpleDateFormat.parse(loginBeen.ctime).getTime();
                                    if (MathUtils.compare(time + "","1498147200000") <= 0){
                                        //老用户
                                        Logs.e("老用户" + time);
                                        sharedPreferences.putBoolean(UserInfo.OLDUSER,true);
                                    }else{
                                        Logs.e("新用户" + time);
                                        sharedPreferences.putBoolean(UserInfo.OLDUSER,false);
                                    }
                                } else {
                                    Logs.e("新用户" + loginBeen.ctime);
                                    sharedPreferences.putBoolean(UserInfo.OLDUSER,false);
                                }

                                //关闭登录和注册两步骤界面，开启开户界面
                                BaseAppManager manager = BaseAppManager.getInstance();
                                if (LoginActivity.class != null){
                                    manager.getActivity(LoginActivity.class).finish();
                                }

                                if (RegisterInputPhoneActivity.class != null){
                                    manager.getActivity(RegisterInputPhoneActivity.class).finish();
                                }

                                if (RegisterValidateActivity.class != null){
                                    manager.getActivity(RegisterValidateActivity.class).finish();
                                }

                                EventBus.getDefault().post(new EventCenter(Constants.EVENT_REFRESH_DATA));//登陆成功通知某些页面进行数据刷新
                                readyGo(OpenAccountBankActivity.class);
                            } catch (Exception e) {
                                new HSToast(mContext).getSingleLongToast(mContext.getString(R.string.date_error)).show();
                                e.printStackTrace();
                            }
                            break;
                        case Constants.REQUESTCODE_100020:
                            //Header值为空--不做任何提示
                            break;
                        default:
                            new HSToast(mContext).getSingleLongToast(adSlideBeen.msg).show();
                            break;
                    }
                }catch (Exception e){
                    new HSToast(mContext).getSingleLongToast(mContext.getString(R.string.date_error)).show();
                    e.printStackTrace();
                }
                closeProgress();
//				注册完成成功之后，进行页面跳转
//				readyGoThenKill();
            }

            @Override
            public void onException(String task_name, String msg) {
                showToast(R.string.check_net);
                closeProgress();
            }
        });

        requestinteractor.getRequestData(TaskConstants.TASK_REGISTER, mContext.getString(R.string.root_url_test) + mContext.getString(R.string.api_index_test)
                + TaskConstants.TASK_REGISTER, Constants.EVENT_DATA, jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, mContext.getString(R.string.api_index_test)
                + TaskConstants.TASK_REGISTER, "", mConfigSP.getShareProf(TaskConstants.TASK_CONFIG), zwgt_data));
    }

    /**
     * 发送验证码，通过反射调用了这个方法发送了短信，改成post请求
     *
     * @param
     */
    protected void sendSms(Object... objs) {
        Logs.e("发送反射注册短信");
        final String phonetext = objs[0].toString();
        //从哪里跳转过来的，如果是注册页面点击的话就就多带一个参数
        final boolean flag = objs.length == 1 ? true:false;
        //发送注册验证码
        StringRequestInteractorImpl requestinteractor = new StringRequestInteractorImpl(new BaseMultiLoadedListener<String>() {
            @Override
            public void onSuccess(String task_name, int event_tag, String data) {
                try{
                    AdSlideBeen adSlideBeen = (AdSlideBeen) GsonTool.getInstanceByJson(AdSlideBeen.class, data);
                    //解析数据吗
                    switch (adSlideBeen.code) {
                        case Constants.REQUESTCODE_000000:
                        case Constants.REQUESTCODE_400001:
                            if (flag) {
                                try {
                                    String decode = AndroidDes3Util.decode(adSlideBeen.data, mConfigSP.getShareProf("config"), (Date.parse(adSlideBeen.timestamp) + "").substring((Date.parse(adSlideBeen.timestamp) + "").length() - 8, (Date.parse(adSlideBeen.timestamp) + "").length()));
                                    String[] split = decode.split("\\n");
                                    //请求验证码成功
                                    Bundle bundle = new Bundle();
                                    //将手机号，验证码带过去
                                    bundle.putString(Extras.PHONE, phonetext);
                                    //获取验证码，准备注册
                                    readyGo(RegisterValidateActivity.class, bundle);
                                } catch (Exception e) {
                                    new HSToast(mContext).getSingleLongToast(mContext.getString(R.string.date_error)).show();
                                    e.printStackTrace();
                                }
                            }
                            new HSToast(mContext).showCustomToast(adSlideBeen.msg);
                            break;
                        case Constants.REQUESTCODE_100020:
                            //Header值为空--不做任何提示
                            break;
                        default:
                            new HSToast(mContext).showCustomToast(adSlideBeen.msg);
                            break;
                    }
                } catch (Exception e){
                    new HSToast(mContext).getSingleLongToast(mContext.getString(R.string.date_error)).show();
                    e.printStackTrace();
                }

                closeProgress();
            }

            @Override
            public void onException(String task_name, String msg) {
                closeProgress();
                showToast(R.string.check_net);
            }
        });

        String zwgt_data = BaseRequestTool2.getFormatedDateString();
        JSONObject map = new JSONObject();
        try {
            map.put("type","1");
            map.put("phone", phonetext);
            map.put("channel","0");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Logs.e("map.tostring" + map.toString());
        JSONObject jsonParams = CommTool.getJSONParams(map, mConfigSP.getShareProf(TaskConstants.TASK_CONFIG), zwgt_data);
        requestinteractor.getRequestData(TaskConstants.TASK_SENDSMS, mContext.getString(R.string.root_url_test) + mContext.getString(R.string.api_index_test)
                + TaskConstants.TASK_SENDSMS, Constants.EVENT_DATA, jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, mContext.getString(R.string.api_index_test) + TaskConstants.TASK_SENDSMS, "", mConfigSP.getShareProf(TaskConstants.TASK_CONFIG), zwgt_data));
    }

}
